<template>
  <div class="page-coupon">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="test-form"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item :label="$t('coupon.couponName') + ':'">
            <el-input
              v-model="searchForm.couponName"
              clearable
              :placeholder="$t('coupon.couponName')"
            />
          </el-form-item>
          <el-form-item :label="$t('coupon.expStatus') + ':'">
            <el-select
              v-model="searchForm.overdueStatus"
              clearable
              :placeholder="$t('coupon.expStatus')"
            >
              <el-option
                v-for="item in overdueStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('coupon.launchStatus') + ':'">
            <el-select
              v-model="searchForm.putonStatus"
              clearable
              :placeholder="$t('coupon.launchStatus')"
            >
              <el-option
                v-for="item in putonStatuList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 日期组件 -->
          <el-form-item :label="$t('coupon.expire') + ':'">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              clearable
              :range-separator="$t('time.tip')"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('time.start')"
              :end-placeholder="$t('time.end')"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="searchChange(true)"
            >
              {{ $t('shopFeature.searchBar.search') }}
            </div>
            <div
              class="default-btn"
              @click="clearSearch"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 搜索栏end -->
    <!-- 表格主体 -->
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('admin:coupon:save')"
          class="default-btn primary-btn"
          @click="addOrUpdateHandle()"
        >
          {{ $t("crud.addTitle") }}
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-con seckill-table">
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <el-table-column
            prop="couponName"
            :label="$t('coupon.couponName')"
            min-width="280"
            fixed="left"
          >
            <template #default="scope">
              <div>
                <span class="table-cell-text line-clamp-one">{{ scope.row.couponName || '' }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="startTime"
            :label="$t('coupon.startTime')"
            min-width="180"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.startTime || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="endTime"
            :label="$t('coupon.endTime')"
            min-width="180"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.endTime || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="couponType"
            :label="$t('coupon.couponType')"
            min-width="150"
          >
            <template #default="scope">
              <div class="tag-text">
                {{ ['', $t("coupon.voucher"), $t("coupon.discountCoupon"),
                    $t("coupon.excCerti")]
                  [scope.row.couponType] }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="overdueStatus"
            :label="$t('coupon.expStatus')"
            min-width="100"
          >
            <template #default="scope">
              <div class="tag-text">
                {{ [$t("coupon.exp"), $t("coupon.notExp")]
                  [scope.row.overdueStatus] }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="putonStatus"
            :label="$t('coupon.launchStatus')"
            min-width="130"
          >
            <template #default="scope">
              <div
                v-if="scope.row.putonStatus !== -1"
                class="tag-text"
              >
                {{ [$t("coupon.waitAutoLaunch"), $t("coupon.launched"), $t("coupon.illOff"), $t("coupon.waitReview"),
                    $t("coupon.waitLaunch")]
                  [scope.row.putonStatus] }}
              </div>
              <div
                v-else
                class="tag-text"
              >
                {{ $t("coupon.cancelLaunch") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            prop="launchTime"
            :label="$t('coupon.timeToMarket')"
            width="180"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.launchTime || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="stocks"
            :label="$t('coupon.stock')"
            sortable
            min-width="100"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.stocks || '0' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="getWay"
            :label="$t('coupon.getWay')"
            width="auto"
          >
            <template #default="scope">
              <span class="tag-text">{{
                [$t("coupon.receiveDirectly"), $t("coupon.exchangeOrSystemIssue")][scope.row.getWay] }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="takeNum"
            :label="$t('dataAnaly.numberOfRe')"
            sortable
            min-width="110"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.takeNum || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="useNum"
            :label="$t('dataAnaly.microMallUsage')"
            sortable
            min-width="160"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.useNum || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            :label="$t('crud.menu')"
            width="180"
            fixed="right"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('admin:coupon:update')"
                  class="default-btn text-btn"
                  @click="addOrUpdateHandle(scope.row.couponId)"
                >
                  {{ scope.row.overdueStatus === 0 ? $t("live.view") : $t("temp.modify") }}
                </div>
                <div
                  v-if="isAuth('admin:coupon:auditApply') && scope.row.putonStatus > 1 && scope.row.putonStatus < 4"
                  class="default-btn text-btn"
                  @click="auditEventHandle(scope.row.couponId)"
                >
                  {{
                    scope.row.putonStatus === 2
                      ? $t("groups.applyForListing")
                      : $t("coupon.waitReview")
                  }}
                </div>
                <div
                  v-if="isAuth('admin:coupon:delete')"
                  class="default-btn text-btn"
                  @click="deleteHandle(scope.row.couponId)"
                >
                  {{ $t("text.delBtn") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 表格主体end -->

    <!-- 下线管理弹窗-->
    <offline-event-handle
      v-if="offlineEventHandleVisible"
      ref="offlineEventRef"
      select-url="/admin/coupon/getOfflineHandleEventByCouponId"
      apply-url="/admin/coupon/auditApply"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'

const Data = reactive({
  theData: null, // 保存上次点击查询的请求条件
  theParams: null, // 保存上次点击查询的请求条件

  search: {
    slot: ''
  },
  dataForm: {
    orderNumber: '',
    status: null
  },
  dateRange: [],
  overdueOptions: [{
    value: 0,
    label: $t('coupon.exp')
  },
  {
    value: 1,
    label: $t('coupon.notExp')
  }],
  PutonOptions: [{
    value: -1,
    label: $t('coupon.cancelLaunch')
  },
  {
    value: 0,
    label: $t('coupon.waitAutoLaunch')
  },
  {
    value: 1,
    label: $t('coupon.launched')
  },
  {
    value: 2,
    label: $t('coupon.illOff')
  },
  {
    value: 3,
    label: $t('coupon.waitReview')
  },
  {
    value: 4,
    label: $t('coupon.waitLaunch')
  }],
  dataList: [],
  dataListLoading: false,
  offlineEventHandleVisible: false,
  dataListSelections: [],
  page: {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  },
  // 头部搜索表单
  searchForm: {
    couponName: null,
    overdueStatus: null,
    putonStatus: null
  },
  overdueStatusList: [
    {
      value: 1,
      label: $t('coupon.notExp')
    }, {
      value: 0,
      label: $t('coupon.exp')
    }
  ],
  putonStatuList: [
    {
      value: -1,
      label: $t('coupon.cancelLaunch')
    },
    {
      value: 0,
      label: $t('coupon.waitAutoLaunch')
    },
    {
      value: 1,
      label: $t('coupon.launched')
    },
    {
      value: 2,
      label: $t('coupon.illOff')
    },
    {
      value: 3,
      label: $t('coupon.waitReview')
    },
    {
      value: 4,
      label: $t('coupon.waitLaunch')
    }
  ]
})

const { dateRange, dataList, offlineEventHandleVisible, page, searchForm, overdueStatusList, putonStatuList } = toRefs(Data)

onMounted(() => {
  getDataList()
})

// 获取数据列表
const getDataList = (page, newData = false) => {
  if (Data.page) {
    const size = Math.ceil(Data.page.total / Data.page.pageSize)
    Data.page.currentPage = (Data.page.currentPage > size ? size : Data.page.currentPage) || 1
  }
  Data.dataListLoading = true

  if (newData || !Data.theData) {
    Data.theParams = JSON.parse(JSON.stringify(Data.searchForm))
    Data.theData = {
      current: page == null ? Data.page.currentPage : page.currentPage,
      size: page == null ? Data.page.pageSize : page.pageSize,
      couponName: Data.dataForm.couponName,
      overdueStatus: Data.dataForm.overdueStatus,
      putonStatus: Data.dataForm.putonStatus,
      startTime: Data.dateRange === null ? null : Data.dateRange[0], // 开始时间
      endTime: Data.dateRange === null ? null : Data.dateRange[1] // 结束时间
    }
  } else {
    Data.theData.current = page == null ? Data.page.currentPage : page.currentPage
    Data.theData.size = page == null ? Data.page.pageSize : page.pageSize
  }
  http({
    url: http.adornUrl('/admin/coupon/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        Data.theData,
        Data.theParams
      ), false
    )
  }).then(({ data }) => {
    Data.dataList = data.records
    Data.page.total = data.total
    Data.page.currentPage = data.current
    Data.dataListLoading = false
  })
}

const router = useRouter()
// 新增 / 修改
const addOrUpdateHandle = (val) => {
  router.push({
    path: '/marketing/coupon/new-coupon',
    query: {
      couponId: val
    }
  })
}

// 删除
const deleteHandle = (id) => {
  const ids = id ? [id] : Data.dataListSelections.map(item => {
    return item.couponId
  })
  ElMessageBox.confirm(`${$t('sys.makeSure')}[${id ? $t('text.delBtn') : $t('sys.batchDelete')}]${$t('text.menu')}?`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/admin/coupon'),
      method: 'delete',
      data: http.adornData(id, false)
    }).then(() => {
      Data.page.total = Data.page.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  })
}

// 条件查询
const searchChange = (newData = false) => {
  Data.page.currentPage = 1
  Data.page.pageSize = 10
  getDataList(Data.page, newData)
}

// 刷新回调用
const refreshChange = () => {
  // this.page = this.$refs.crud.$refs.tablePage.defaultPage
  getDataList(Data.page)
}

const offlineEventRef = ref()
// 下线管理
const auditEventHandle = (id) => {
  Data.offlineEventHandleVisible = true
  nextTick(() => {
    offlineEventRef.value.init(id)
  })
}

const clearSearch = () => {
  Data.dateRange = []
  Data.searchForm.couponName = null
  Data.searchForm.overdueStatus = null
  Data.searchForm.putonStatus = null
}

// 每页数量变更
const handleSizeChange = (val) => {
  Data.page.pageSize = val
  Data.getDataList()
}

// 页数变更
const handleCurrentChange = (val) => {
  Data.page.currentPage = val
  getDataList()
}
</script>

<style lang="scss" scoped></style>
